package com.yulan.bankback.service.ip.impl;

import com.yulan.bankback.entity.model.admin.GeoIp;
import com.yulan.bankback.service.ip.IpService;
import net.ipip.ipdb.City;
import net.ipip.ipdb.CityInfo;
import net.ipip.ipdb.IPFormatException;
import net.ipip.ipdb.InvalidDatabaseException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class IpServiceImpl implements IpService {


    @Value("${ip.geo-db}")
    private String filePath;


    private static final AtomicInteger inc = new AtomicInteger(0);

    @Override
    public GeoIp findCityByIp(String ip) throws IPFormatException, IOException {
        String fileName = filePath;
        City db = new City(fileName);
        // 将整形表示的ip地址转换为字符串表示,ip可以从业务逻辑中获取,  Long.parseLong(ip)
        // findInfo方法中"CN"表示中国,返回是的city实体
        CityInfo info = db.findInfo(ip, "CN");
        return info == null ? null : new GeoIp(inc.getAndIncrement(),info.getCountryName(),
                info.getRegionName(), info.getCityName(),ip);
    }



}
